﻿using System.Collections.Generic;
using Hidistro.Core;
using Hidistro.Core.Enums;
using Hidistro.Entities;
using Hidistro.Entities.Commodities;
using Hidistro.SaleSystem.Catalog;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;

namespace Hidistro.UI.SaleSystem.Tags
{
    public class wnxd_HotBrand : WebControl
    {
        private Database database = DatabaseFactory.CreateDatabase();


        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(this.RendHtml());
        }
        public string RendHtml()
        {
            StringBuilder builder = new StringBuilder();
            IList<DataRow> info = this.GetHotBrands(this.maxnum);
            for (int i = 0; i < info.Count; i++)
            {
                builder.Append("<div class=\"pro8\" style=\"height:310px;\">");
                builder.AppendFormat("<a href=\"{0}\"><img src=\"{1}\" width=\"230px\"><div class=\"brand_bg\"></div><div class=\"brand_name\">{2}</div></a>", Globals.GetSiteUrls().SubBrandDetails((int)info[i]["BrandId"], info[i]["RewriteName"]), Globals.GetImgUrl(info[i]["ImageUrl"].ToString()), info[i]["BrandName"]);
                builder.Append("</div>");
            }
            return builder.ToString();
        }
        public int maxnum { get; set; }
        private DataTable sql_call(string sql)
        {
            using (DbCommand cmd = database.GetSqlStringCommand(sql))
            using (IDataReader reader = database.ExecuteReader(cmd))
            {
                return DataHelper.ConverDataReaderToDataTable(reader);
            }
        }
        private IList<DataRow> GetHotBrands(int MaxNum)
        {
            DataTable info = this.sql_call("select t1.BrandId,t2.BrandName,t1.ThumbnailUrl310 as ImageUrl,t2.RewriteName from Hishop_Products t1 left join (select BrandName,RewriteName,BrandId from Hishop_BrandCategories) as t2 on t1.BrandId=t2.BrandId where MainCategoryPath like '9|%' and t1.BrandId is not null order by ShowSaleCounts desc");
            IList<DataRow> v = new List<DataRow>();
            int i = 0;
            foreach (DataRow row in info.Rows)
            {
                if (i == MaxNum) break;
                if (!this.IndexOfKey(v, "BrandId", row["BrandId"]))
                {
                    v.Add(row);
                    i++;
                }
            }
            return v;
        }
        private bool IndexOfKey(IList<DataRow> list, string Key, object Value)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i][Key].Equals(Value))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
